<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/6
 * Time: 17:47
 */

namespace App\Model\Backstage;


use App\Model\Account\Administration;
use App\Model\Base;
use App\Model\Common\Position;
use App\ServiceHandler\Common\DepartmentService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Auth;
use App\Model\Account\SystemType;
use Qiniu\Auth as qiniuAuth;
use Qiniu\Storage\BucketManager;


class User extends Model
{
    protected $table;
    protected $request;
//    protected $cf_source;//房客源提醒表
//    protected $room_info;
//    protected $customer;

    public function __construct()
    {
        $this->table = 'user';
//        $this->cf_source = 'customer_follow_source';
//        $this->room_info = 'room_info';
//        $this->customer = 'customers';
    }

    /**
     * 根据员工ID 获取员工类型
     * @param $uId
     * @return mixed
     */
    public  function getUserType()
    {
        $type = DB::table('user')->where('u_id', $this->uid)->value('u_type');
        return ['type' => $type, 'uid' => $this->uid];
    }

    /**
     * @param array $map
     * @return mixed
     * 获取用户列表
     */
    public function getUserList ($map = [], $pageLimit)
    {
        $list = DB::table('user')
            ->leftJoin('staff', 'u_id', '=', 'area_manager_id')
            ->leftJoin('department', 'u_d_id', '=', 'department.id')
            ->leftJoin('position', 'post', '=', 'p_id')
            ->where($map)
            ->select('u_id', 'u_d_id', 'name', 'avatar', 'u_username', 'u_account_number', 'u_last_ip',
                DB::raw('from_unixtime(u_last_time) AS u_last_time'),'u_status', 'u_type',
                DB::raw('from_unixtime(h_user.created_at) AS created_at'),DB::raw('from_unixtime(h_user.updated_at) AS updated_at'),
                'sex', 'birthday', 'jiguan', 'nation', 'college', 'political_face', 'speciality', 'record_type', 'people_num',
                'phone', 'email', 'staff.address', 'bank_num', 'bank_remark', 'personal_profile','p_id', 'p_name as post',
                DB::raw('from_unixtime(entry_time) AS entry_time'),DB::raw('from_unixtime(separation_time) AS separation_time'),
                'source', 'remark', 'authories')
            ->orderBy('u_id', 'desc')
            ->paginate($pageLimit);
        if (sizeof($list) == 0) {
            return false;
        }
        return $list;
    }


    //删除图片（修改删除）
    public static  function delImage($fileName, $uid){
        $fileName = basename($fileName);
        $auth = new qiniuAuth(env('QINIU_ACCESSKEY'), env('QINIU_SECRETKEY'));
        $uploadMgr = new BucketManager($auth);
        if ($uid != 0) {//修改时候的删除
//            $avatar = DB::table('staff')->where('area_manager_id',$uid)->value('avatar');
            //删除七牛资源操作
            $qiniuRel = $uploadMgr->delete(env('QINIU_BUCKET'),$fileName);
            if($qiniuRel === null){
                return DB::table('staff')
                    ->where('area_manager_id',$uid)
                    ->update([
                        'avatar'   => '',
                        's_update_time' => time()
                    ]);
            } else {
                return false;
            }
        } else { //添加时候的删除
            $qiniuRel = $uploadMgr->delete(env('QINIU_BUCKET'),$fileName);
            if($qiniuRel === null){
                return true;
            }
            return false;
        }
    }

    /**
     * @param $params
     * @return mixed
     * 添加中介公司用户
     */
    public function addUser ($params)
    {
        $time = time();
        $params['created_at'] =  $time;
        //账号
        $u_account_number = $params['u_b_id'].'_'.$params['phone'];
        $id = DB::table($this->table)
            ->where('u_account_number', $u_account_number)
            ->value('u_id');
        if ($id) {
            return -1;
        }
        //开启事务
        DB::beginTransaction();
        $uid = $this->insertGetId([
            'u_b_id'           =>  $params['u_b_id'],
            'u_d_id'           =>  $params['u_d_id'],
            'u_username'       =>  $params['u_username'],
            'u_account_number' =>  $u_account_number,
            'u_password'       =>  Hash::make($params['u_password']),
            'u_type'           =>  1,
            'u_status'         =>  1,
            'created_at'       =>  $time,
            'updated_at'       =>  $time,
            'is_del'           =>  0
        ]);
        $sid = DB::table('staff')->insertGetId([
            'branch_id'       =>  $params['u_b_id'],
            'area_manager_id' =>  $uid,
            'sex'             =>  $params['sex'],
            'avatar'          =>  $params['avatar'],
            'birthday'        =>  $params['birthday'],
            'jiguan'          =>  $params['jiguan'],
            'nation'          =>  $params['nation'],
            'college'         =>  $params['college'],
            'political_face'  =>  $params['political_face'],
            'speciality'      =>  $params['speciality'],
            'record_type'     =>  $params['record_type'],
            'people_num'      =>  $params['people_num'],
            'phone'           =>  $params['phone'],
            'email'           =>  $params['email'],
            'address'         =>  $params['address'],
            'bank_num'        =>  $params['bank_num'],
            'bank_remark'     =>  $params['bank_remark'],
            'personal_profile'=>  $params['personal_profile'],
            'post'            =>  $params['post'],
            'entry_time'      =>  $time,
            'source'          =>  $params['source'],
            'remark'          =>  $params['remark']
        ]);
        //根据选择的职务的不同   分配给该员工不同的权限
        $d_authories = DB::table('position')->where('p_id', $params['post'])->value('p_authories');
        $uidTwo = DB::table($this->table)->where('u_id', $uid)->update(['authories' => $d_authories, 'updated_at' => $time]);
        if ($uid && $sid && $uidTwo) {
            DB::commit();
            $content = '添加员工：'.'姓名 => '.$params['u_username'].' ID => '.$uid;
            $log = new Log();
            $log->addlog($params['sId'],$params['uId'],10,$content);
            return $u_account_number;

        } else {
            DB::rollback();
            return false;
        }

    }


    /**
     * @param $map
     * @param $params
     * @return mixed
     * 修改中介公司用户信息
     */
    public function saveUser ($params)
    {
        $oldUserInfo = $this->getUserInfo($params['u_id']);
        $time = time();
        //开启事务
        DB::beginTransaction();
        $uid = $this->where('u_id',$params['u_id'])->update([
            'u_d_id'           =>  $params['u_d_id'],
            'u_username'       =>  $params['u_username'],
            'updated_at'       =>  $time,
            'u_status'         =>  $params['u_status']
        ]);
        //修改 状态为离职的时候   离职时间为当前时间
        if ($params['u_status'] == 3) {
            $separation_time = $time;
        } else {
            $separation_time = null;
        }
        $sid = DB::table('staff')->where('area_manager_id', $params['u_id'])->update([
            'sex'             =>  $params['sex'],
            'avatar'          =>  $params['avatar'],
            'birthday'        =>  $params['birthday'],
            'jiguan'          =>  $params['jiguan'],
            'nation'          =>  $params['nation'],
            'college'         =>  $params['college'],
            'political_face'  =>  $params['political_face'],
            'speciality'      =>  $params['speciality'],
            'record_type'     =>  $params['record_type'],
            'people_num'      =>  $params['people_num'],
            'phone'           =>  $params['phone'],
            'email'           =>  $params['email'],
            'address'         =>  $params['address'],
            'bank_num'        =>  $params['bank_num'],
            'bank_remark'     =>  $params['bank_remark'],
            'personal_profile'=>  $params['personal_profile'],
            'post'            =>  $params['post'],
            'source'          =>  $params['source'],
            'remark'          =>  $params['remark'],
            's_update_time'   =>  $time,
            'separation_time' =>  $separation_time
        ]);
        $d_authories = DB::table('position')->where('p_id', $params['post'])->value('p_authories');
        $uidTwo = DB::table($this->table)->where('u_id', $uid)->update(['authories' => $d_authories, 'updated_at' => time()]);
        if ($uid && $sid && $uidTwo) {
            DB::commit();
            $content = '修改员工信息：';
            if($params['u_d_id'] != $oldUserInfo->u_d_id){
                $content .= ' 部门 '.$oldUserInfo->u_d_id.' => '.$params['u_d_id'];
            }
            if($params['u_username'] != $oldUserInfo->u_username){
                $content .= ' 名字'.$oldUserInfo->u_username. ' => '.$params['u_username'];
            }

            if($params['college'] != $oldUserInfo->college){
                $content .= ' 毕业院校'.$oldUserInfo->college. ' => '.$params['college'];
            }
            if($params['speciality'] != $oldUserInfo->speciality){
                $content .= ' 专业'.$oldUserInfo->speciality. ' => '.$params['speciality'];
            }
            if($params['people_num'] != $oldUserInfo->people_num){
                $content .= ' 身份证号码 '.$oldUserInfo->people_num.' => '.$params['people_num'];
            }
            if($params['phone'] != $oldUserInfo->phone){
                $content .= ' 联系电话'.$oldUserInfo->phone. ' => '.$params['phone'];
            }
            if($params['email'] != $oldUserInfo->email){
                $content .= ' 电子邮箱'.$oldUserInfo->email. ' => '.$params['email'];
            }
            if($params['bank_num'] != $oldUserInfo->bank_num){
                $content .= ' 银行卡号 '.$oldUserInfo->bank_num.' => '.$params['bank_num'];
            }
            if($params['bank_remark'] != $oldUserInfo->bank_remark){
                $content .= ' 银行名字'.$oldUserInfo->bank_remark. ' => '.$params['bank_remark'];
            }
            if($params['post'] != $oldUserInfo->post){
                $content .= ' 职务'.Position::getNameForPid($oldUserInfo->post). ' => '.Position::getNameForPid($params['post']);
            }
            if($params['source'] != $oldUserInfo->source){
                $content .= ' 来源'.$oldUserInfo->source. ' => '.$params['source'];
            }
            $log = new Log();
            $log->addlog($params['store_id'],$params['uid'],10,$content);
            return true;

        } else {
            DB::rollback();
            return false;
        }
    }

    public function getUserInfo($id){
        return  DB::table('user')
                    ->where('u_id',$id)
                    ->leftjoin('staff','area_manager_id','u_id')
                    ->select('u_d_id','u_username','u_account_number','u_password','sex','birthday','jiguan',
                        'nation','college','political_face','speciality','record_type','people_num','phone',
                        'email','address','bank_num','bank_remark','post','source')->first();

    }
    /**
     * @param $uid
     * @return mixed
     * 删除中介公司用户信息
     */
    public function delUser($uid,$thisUser,$thisUserDepartment)
    {
        $oldStatus = DB::table('user')->where('u_id',$uid)->value('is_del');
        $oldname = DB::table('user')->where('u_id',$uid)->value('u_username');
       if($oldStatus == 0){
            //删除操作
            $newStatus = 1;
            $result =  $this->where(['u_id' => $uid])->update(['is_del' => $newStatus,'updated_at'=>time(),'u_deluser'=>$thisUser,'u_del_department'=>$thisUserDepartment]);
            if($result){
                $log = new Log();
                $content = '删除员工：'.'ID => '.$uid.' 姓名 => '.$oldname;
                $log->addlog($thisUserDepartment,$thisUser,10,$content);
            }
           return $result;
        }elseif($oldStatus == 1){
            //恢复操作
            $newStatus = 0;
            $result =  $this->where(['u_id' => $uid])->update(['is_del' => $newStatus,'updated_at'=>time(),'u_deluser'=>'','u_del_department'=>'']);
           if($result){
               $log = new Log();
               $content = '恢复员工：'.'ID => '.$uid.' 姓名 => '.$oldname;
               $log->addlog($thisUserDepartment,$thisUser,10,$content);
           }
           return $result;
        }else{
            return -1;
        }


    }

    //硬删除
    public function DeletePermanently($uid,$thisUser,$thisUserDepartment){
        $oldname = DB::table('user')->where('u_id',$uid)->value('u_username');
             //硬操作
            $result =  $this->where(['u_id' => $uid])->update(['is_del' => 2,'updated_at'=>time(),'u_deluser'=>'','u_del_department'=>'']);
            if($result){
                $log = new Log();
                $content = '彻底删除员工：'.'ID => '.$uid.' 姓名 => '.$oldname;
                $log->addlog($thisUserDepartment,$thisUser,10,$content);
            }
            return $result;

    }

    /*
     * 回收站员工列表
     * 部门名称 员工Id 员工姓名 职务 员工电话 简介 删除人 删除时间
     */
    public function recycleBinList($pageLimit,$where,$keywords){
        if($keywords == ''){
            $list = DB::table('user as u')
                ->leftjoin('department as d','u.u_d_id','d.id')
                ->leftjoin('staff as s','u.u_id','s.area_manager_id')
                ->leftjoin('user as uone', 'u.u_deluser', 'uone.u_id')
                ->leftjoin('department as done', 'u.u_del_department', '=', 'done.id')
                ->where($where)
                ->select('d.name','u.u_id','u.u_username', 's.avatar', 's.post','s.phone','s.personal_profile','uone.u_username as u_deluser','done.name as u_del_department',
                    DB::raw('from_unixtime(h_u.updated_at) as updated_at'))
                ->orderBy('u.updated_at','desc')
                ->paginate($pageLimit);
        }else{
            $list = DB::table('user as u')
                ->leftjoin('department as d','u.u_d_id','d.id')
                ->leftjoin('staff as s','u.u_id','s.area_manager_id')
                ->leftjoin('user as uone', 'u.u_deluser', 'uone.u_id')
                ->leftjoin('department as done', 'u.u_del_department', '=', 'done.id')
                ->where($where)
                ->where(function ($query) use($where, $keywords){
                    $query->where($where)->where('u.u_username', 'like', '%'.$keywords.'%');//员工名字
                })
                ->select('d.name','u.u_id','u.u_username','s.post','s.phone','s.personal_profile','uone.u_username as u_deluser','done.name as u_del_department',
                    DB::raw('from_unixtime(h_u.updated_at) as updated_at'))
                ->orderBy('u.updated_at','desc')
                ->paginate($pageLimit);
        }
        if (sizeof($list) == 0) {
            return false;
        }
        return $list;
    }


    /**上级重置员工密码
     * @param $uid 员工ID
     * @return mixed
     */
    public static function resetPassword($uid)
    {
        return DB::table('user')->where('u_id', $uid)->update(['u_password' => Hash::make(123456), 'updated_at' => time()]);
    }

    /**
     * 根据员工ID 获取该员工的名字
     */
    public static function getUserNameForId($id)
    {
        return DB::table('user')->where('u_id', $id)->value('u_username');
    }
    /**修改密码
     * @param $newPassword
     * @return mixed
     */
    public static function updatePassword($newPassword)
    {
        $uId = Auth::user()->u_id;
        return DB::table('user')->where('u_id', $uId)->update([
            'u_password'     => Hash::make($newPassword),
            'updated_at'               => time()
        ]);
    }

    /**
     * @param $params
     * @return bool|string
     * 用户登陆
     */
    public function loginUser ($params, $province, $city, $IP)
    {
        $user_info = User::where('u_account_number', $params['u_account_number'])->first();
        if (!$user_info) {
            return -4;//账号不存在
        }
        if ($user_info->u_status == 2) {
            return -5;//账号被禁用
        }
        if ($user_info->is_del == 1 || $user_info->is_del == 2) {
            return -6;//账号被管理者删除
        }
        // 判断密码是否正确
        if (Hash::check($params['u_password'], $user_info->u_password)){
            //查询该账号所属的公司状态
//            $status = DB::table('account_number_manager')->where('anm_id', $user_info->u_b_id)->value('anm_status');
            $anmData = DB::table('account_number_manager')->where('anm_id', $user_info->u_b_id)->select('anm_status', 'anm_current_reminding', 'anm_expirytime')->first();
            $status = $anmData->anm_status;//中介公司账号状态

            if ($status == 2) {
                //公司还在审核中不能登录
                return -1;
            } elseif ($status == 3) {
                //公司账号到期没有续费无法登录
                 return -2;
            } elseif($status == 1) {
                // 生成随机字符串存数据库 用户认证用
                $apiToken = str_random(60);
                $data['u_api_token'] = $apiToken;
                $data['u_last_time'] = time();
                $data['u_last_ip'] = $_SERVER["REMOTE_ADDR"];
                $this->where(['u_id'=>$user_info->u_id])->update($data);
                unset($user_info['u_password']);
                $res['token'] = $apiToken;//返回TOKEN

                //中介公司 到期提前一个月提醒
                $anm_current_reminding = $anmData->anm_current_reminding;//中介公司账号到期提前一个月的提醒时间
                $anm_expirytime = $anmData->anm_expirytime;//中介公司账号到期时间
                $res['expiration_reminding'] = '';
                if (time() >= intval($anm_current_reminding)) {
                    $res['expiration_reminding'] = '距离您系统到期使用时间还有'.ceil((intval($anm_expirytime)-time())/24/60/60).'天！ 请您及时续费，以防您无法正常使用。(提前30天通知信息)';
                }
                //当前登录账号的权限
                $authoriesArray = explode(',', $user_info->authories);
                $res['authories'] =[];//返回该用户的权限
                if (sizeof($authoriesArray) != 0) {
                    foreach($authoriesArray as $k=>$v) {
                        $nmtype = explode('|', $v);
                        if ($v) {
                            array_push($res['authories'], $nmtype[2]);
                        }
                    }
                }

                $res['did']=$user_info->u_d_id;//当前登录人部门ID
                $res['dname']= DB::table('department')->where('id', $user_info->u_d_id)->value('name');//当前登录人部门名称
                $res['uid']=$user_info->u_id;//当前登录人ID
                $res['uname']=$user_info->u_username;//当前登录人名称
                //当前公司的系统管理组部门ID
                $res['system_sid'] = DB::table('department')->where('c_id', $user_info->u_b_id)->where('d_superior_id', 0)->value('id');
                $res['u_type'] = $user_info->u_type;//当前用户的类型
                $res['end_time'] = strtotime(date('Y-m-d', time()).' 23:59:59');//当天的结束时间戳
                $res['user_down'] = DB::table('user')->where('u_b_id', $user_info->u_b_id)->where('u_d_id', $res['did'])->where('is_del', 0)->select('u_id', 'u_username')->get();//当前用户所在部门中所有的员工

                $log = new Log();
                $log->addlog($user_info->u_d_id, $user_info->u_id, 1, $IP.' 地址：'.$province.' '.$city, $user_info->u_b_id);
                return $res;
            }else {
                //未知状态 请联系管理员
                return -3;
            }

        }else{
            return false;
        }
    }

    /**
     * 根据员工的ID   修改员工的权限
     */
    public static function editUserPermission($params)
    {
        $d_authories = explode(',', $params['authories']);
        $arr = DB::table('nosplit_authority as na')
            ->leftJoin('nosplit_module as nm', 'na.module_id', '=', 'nm.id')
            ->whereIn('na.id', $d_authories)
            ->select(DB::raw('GROUP_CONCAT(h_nm.nm_type) as nm_type'), DB::raw('GROUP_CONCAT(h_na.module_id) as module_id'), DB::raw('GROUP_CONCAT(h_na.id) as id'))
            ->get();
        $type = explode(',', $arr[0]->nm_type);//模块类型
        $module_id = explode(',', $arr[0]->module_id);//模块ID
        $id = explode(',', $arr[0]->id);//权限ID
        $authories = '';
        foreach ($type as $k=>$v) {
            $authories .= $v.'|'.$module_id[$k].'|'.$id[$k].',';
        }
        return DB::table('user')->where('u_id', $params['u_id'])->update(['authories' => $authories, 'updated_at' => time()]);
    }

    /**
     *APP端   根据员工ID  修改员工头像
     */
    public static function editAvatar($uid, $avatar)
    {
        return DB::table('staff')->where('area_manager_id', $uid)->update(['avatar' => $avatar, 's_update_time' => time()]);
    }


}